package com.atguigu.tingshu.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.user.UserListenProcess;
import com.atguigu.tingshu.user.service.UserListenProcessService;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.user.UserListenProcessVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@SuppressWarnings({"all"})
public class UserListenProcessServiceImpl implements UserListenProcessService {

	@Autowired
	private MongoTemplate mongoTemplate;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private RabbitService rabbitService;

	@Override
	public BigDecimal getTrackBreakSecond(Long trackId, Long userId) {
		//集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//设定查询条件
		Query query = new Query();
		query.addCriteria(Criteria.where("trackId").is(trackId).and("userId").is(userId));
		List<UserListenProcess> processList = mongoTemplate.find(query, UserListenProcess.class, collectionName);
		if (CollectionUtils.isEmpty(processList)){
			return new BigDecimal(0.00);
		}
		return processList.get(0).getBreakSecond();
	}

	@Override
	public void updateListenProcess(UserListenProcessVo userListenProcessVo, Long userId) {
		//集合名称
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		//设定查询条件
		Query query = new Query();
		query.addCriteria(Criteria.where("trackId").is(userListenProcessVo.getTrackId()).and("userId").is(userId));
		List<UserListenProcess> processList = mongoTemplate.find(query, UserListenProcess.class, collectionName);
		if (CollectionUtils.isEmpty(processList)){
			//没有播放记录，添加进数据库
			UserListenProcess userListenProcess = new UserListenProcess();
			userListenProcess.setUserId(userId);
			userListenProcess.setTrackId(userListenProcessVo.getTrackId());
			userListenProcess.setAlbumId(userListenProcessVo.getAlbumId());
			userListenProcess.setBreakSecond(userListenProcessVo.getBreakSecond());
			userListenProcess.setIsShow(1);
			userListenProcess.setCreateTime(new Date());
			userListenProcess.setUpdateTime(new Date());
			mongoTemplate.insert(userListenProcess,collectionName);
		}else {
			//有播放记录，更新播放记录
			UserListenProcess process = processList.get(0);
			process.setBreakSecond(userListenProcessVo.getBreakSecond());
			process.setUpdateTime(new Date());
			mongoTemplate.save(process,collectionName);
		}
		//修改专辑和声音的播放量，播放量+1（每名用户每天只能增加一次播放量）
		String key = "user:track:" + userId + ":" + userListenProcessVo.getTrackId();
		Boolean result = redisTemplate.opsForValue().setIfAbsent(key, 1, 1, TimeUnit.DAYS);
		if (result){
			//是第一次播放，播放量+1
			TrackStatMqVo vo = new TrackStatMqVo();
			vo.setAlbumId(userListenProcessVo.getAlbumId());
			vo.setTrackId(userListenProcessVo.getTrackId());
			vo.setCount(1);
			vo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-", ""));
			vo.setStatType(SystemConstant.TRACK_STAT_PLAY);
			try {
				rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSON.toJSONString(vo));
			} catch (Exception e) {
				redisTemplate.delete(key);
			}
		}
	}

	@Override
	public Map<String, Object> getLatelyTrack(Long userId) {
		Map<String, Object> map = new HashMap<>();
		//设定查询条件，查找最新的一条播放记录
		Query query = new Query();
		query.with(Sort.by(Sort.Direction.DESC, "updateTime")).limit(1);
		String collectionName = MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.USER_LISTEN_PROCESS, userId);
		List<UserListenProcess> processList = mongoTemplate.find(query, UserListenProcess.class, collectionName);
		if (!CollectionUtils.isEmpty(processList)){
			//有播放记录
			UserListenProcess userListenProcess = processList.get(0);
			map.put("trackId",userListenProcess.getTrackId());
			map.put("albumId",userListenProcess.getAlbumId());
		}
		return map;
	}
}
